USE [RobotInstaller];
GO

CREATE OR ALTER VIEW dbo.vw_PackageList
AS
SELECT
    p.Id,
    p.PackageCode,
    p.PackageName,
    p.PackageType,
    p.Description,
    p.IsActive,
    p.CreatedAt,
    p.UpdatedAt,
    p.CreatedByUserId,
    u.Username AS CreatedByUsername,
    latest.Id AS LatestVersionId,
    latest.Version AS LatestVersion,
    latest.ReleaseDate AS LatestReleaseDate,
    latest.FilePath AS LatestFilePath,
    latest.DockerImage AS LatestDockerImage,
    version_count.VersionCount
FROM dbo.Packages AS p
INNER JOIN dbo.Users AS u
    ON u.Id = p.CreatedByUserId
OUTER APPLY
(
    SELECT TOP (1)
        pv.Id,
        pv.Version,
        pv.ReleaseDate,
        pv.FilePath,
        pv.DockerImage
    FROM dbo.PackageVersions AS pv
    WHERE pv.PackageId = p.Id
    ORDER BY pv.IsLatest DESC, pv.ReleaseDate DESC, pv.UploadedAt DESC
) AS latest
OUTER APPLY
(
    SELECT COUNT_BIG(*) AS VersionCount
    FROM dbo.PackageVersions AS pv
    WHERE pv.PackageId = p.Id
) AS version_count;
GO

CREATE OR ALTER VIEW dbo.vw_PackageVersionList
AS
SELECT
    pv.Id,
    pv.PackageId,
    p.PackageCode,
    p.PackageName,
    p.PackageType,
    pv.Version,
    pv.FilePath,
    pv.DockerImage,
    pv.FileChecksumSha256,
    pv.FileSizeBytes,
    pv.ChangeLog,
    pv.ReleaseDate,
    pv.UploadedAt,
    pv.IsLatest,
    pv.IsDeprecated
FROM dbo.PackageVersions AS pv
INNER JOIN dbo.Packages AS p
    ON p.Id = pv.PackageId;
GO

CREATE OR ALTER VIEW dbo.vw_ApplicationList
AS
SELECT
    a.Id,
    a.AppCode,
    a.AppName,
    a.AppVersion,
    a.Description,
    a.Status,
    a.Notes,
    a.OpenUrl,
    a.CreatedAt,
    a.UpdatedAt,
    a.CreatedByUserId,
    u.Username AS CreatedByUsername,
    COUNT_BIG(ap.Id) AS PackageCount
FROM dbo.Applications AS a
INNER JOIN dbo.Users AS u
    ON u.Id = a.CreatedByUserId
LEFT JOIN dbo.ApplicationPackages AS ap
    ON ap.ApplicationId = a.Id
GROUP BY
    a.Id,
    a.AppCode,
    a.AppName,
    a.AppVersion,
    a.Description,
    a.Status,
    a.Notes,
    a.OpenUrl,
    a.CreatedAt,
    a.UpdatedAt,
    a.CreatedByUserId,
    u.Username;
GO

CREATE OR ALTER VIEW dbo.vw_ApplicationPackageDetails
AS
SELECT
    ap.Id,
    ap.ApplicationId,
    a.AppCode,
    a.AppName,
    a.AppVersion,
    a.OpenUrl AS AppOpenUrl,
    ap.PackageId,
    p.PackageCode,
    p.PackageName,
    p.PackageType,
    ap.SelectedVersionId,
    pv.Version AS SelectedVersion,
    pv.FilePath,
    pv.DockerImage,
    ap.AddedAt,
    ap.Notes
FROM dbo.ApplicationPackages AS ap
INNER JOIN dbo.Applications AS a
    ON a.Id = ap.ApplicationId
INNER JOIN dbo.Packages AS p
    ON p.Id = ap.PackageId
LEFT JOIN dbo.PackageVersions AS pv
    ON pv.Id = ap.SelectedVersionId;
GO

PRINT N'RobotInstaller views were created successfully.';
GO
