const core = require('@actions/core');
const fetch = require('node-fetch');
const fs = require('fs');
const FormData = require('form-data');

(async () => {
  try {
    const token = process.env.GITEA_TOKEN;
    const serverUrl = process.env.GITEA_SERVER_URL;
    const repo = process.env.GITEA_REPOSITORY;
    const tag = core.getInput('tag');
    const title = core.getInput('title');
    const draft = core.getInput('draft') === 'true';
    const files = core.getInput('files');

    // Create the release
    const releaseRes = await fetch(`${serverUrl}/api/v1/repos/${repo}/releases`, {
      method: 'POST',
      headers: {
        Authorization: `token ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        tag_name: tag,
        name: title,
        draft: draft
      })
    });

    if (!releaseRes.ok) {
      throw new Error(`Failed to create release: ${releaseRes.status} ${await releaseRes.text()}`);
    }

    const releaseData = await releaseRes.json();
    const uploadUrl = `${serverUrl}/api/v1/repos/${repo}/releases/${releaseData.id}/assets`;

    // Upload files
    if (files) {
      const fileList = files.split(',').map(f => f.trim());
      for (const file of fileList) {
        const form = new FormData();
        form.append('attachment', fs.createReadStream(file));

        const uploadRes = await fetch(uploadUrl, {
          method: 'POST',
          headers: {
            Authorization: `token ${token}`
          },
          body: form
        });

        if (!uploadRes.ok) {
          throw new Error(`Failed to upload file ${file}: ${uploadRes.status} ${await uploadRes.text()}`);
        }

        core.info(`✅ Uploaded: ${file}`);
      }
    }
  } catch (err) {
    core.setFailed(err.message);
  }
})();
